package com.sky.utils;

import com.sky.constant.CompanyConstant;
import com.sun.mail.smtp.SMTPSendFailedException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import net.jodah.expiringmap.ExpiringMap;

/**
 * @author jianKangS1
 * @date 2023/12/20
 */
public class MailUtils {

  public static ExpiringMap<String, String> expiringMap= ExpiringMap.builder()
            .expiration(3,TimeUnit.MINUTES) // 过期时间为3min
            .build();

  /**
   * @param length
   * @return {@link String }
   * @description
   */
  public static String generateVerifyCode(int length) {
    // 生成length位数字验证码
    Random random = new Random();
    String verifyCode = "";
    for (int i = 0; i < length; i++) {
      Integer num = random.nextInt(10);
      verifyCode += num.toString();
    }
    return verifyCode;
  }
  /**
   * @param fromEmail 发送人的邮箱
   * @param pwd       发送人的授权码
   * @param recevices 接收人的邮箱
   * @param code      验证码
   * @return boolean
   * @description
   */
  private static boolean sendEmail(String fromEmail, String pwd,
      String recevices, String code) {
    Properties props = new Properties();
    props.setProperty("mail.transport.protocol", "smtp");    //使用smpt的邮件传输协议
    props.setProperty("mail.smtp.host", "smtp.qq.com");    //主机地址
    props.setProperty("mail.smtp.auth", "true");    //授权通过

    Session session = Session.getInstance(props);    //通过我们的这些配置，得到一个会话程序

    try {

      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(fromEmail));    //设置发件人
      message.setRecipient(MimeMessage.RecipientType.TO,
          new InternetAddress(recevices, "用户", "utf-8"));    //设置收件人
      message.setSubject(CompanyConstant.COMPANY_NAME + "验证码", "utf-8");    //设置主题
      message.setSentDate(new Date());

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
      String str =
          "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body><p style='font-size: 20px;font-weight:bold;'>尊敬的用户，您好！</p>"
              + "<p style='text-indent:2em; font-size: 20px;'>欢迎使用geers齿轮预测平台，您本次的注册码是 "
              + "<span style='font-size:30px;font-weight:bold;color:red'>" + code
              + "</span>，3分钟之内有效，请尽快使用！</p>"
              + "<p style='text-align:right; padding-right: 20px;'"
              + "<a href='http://www.hyycinfo.com' style='font-size: 18px'>土豆片geers齿轮预测平台</a></p>"
              + "<span style='font-size: 18px; float:right; margin-right: 60px;'>" + sdf.format(
              new Date()) + "</span></body></html>";

      Multipart mul = new MimeMultipart();  //新建一个MimeMultipart对象来存放多个BodyPart对象
      BodyPart mdp = new MimeBodyPart();  //新建一个存放信件内容的BodyPart对象
      mdp.setContent(str, "text/html;charset=utf-8");
      mul.addBodyPart(mdp);  //将含有信件内容的BodyPart加入到MimeMultipart对象中
      message.setContent(mul); //把mul作为消息内容

      message.saveChanges();

      //创建一个传输对象
      Transport transport = session.getTransport("smtp");

      //建立与服务器的链接  465端口是 SSL传输
      transport.connect("smtp.qq.com", 587, fromEmail, pwd);

      //发送邮件
      transport.sendMessage(message, message.getAllRecipients());

      //关闭邮件传输
      transport.close();

    } catch (SMTPSendFailedException e) {
      return false;
    } catch (AddressException e) {
      return false;
    } catch (UnsupportedEncodingException e) {
      return false;
    } catch (MessagingException e) {
      return false;
    }

    return true;
  }

  /**
   * 静态测试
   *
   * @param receives
   * @param code
   * @return boolean
   * @description
   */
  public static boolean sendQQMail(String receives, String code) {
    return MailUtils.sendEmail("1539598540@qq.com", "ponnipetcpzfgggb", receives, code);
  }

  /**
   * 正则表达式，检测邮箱是否合法
   *
   * @param email
   * @return boolean
   * @description
   */
  public static boolean checkMailVaild(String email) {
    // 判断邮箱是否合法
    String regex = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
    Pattern pattern = Pattern.compile(regex);
    return pattern.matcher(email).matches();
  }

  /**
   * @param args
   * @description
   */
  public static void main(String[] args) {
    System.out.println(MailUtils.sendQQMail("1539@qq.com", "123"));
  }
}

